package org.subside.Study.login.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.subside.Study.Mq.amqp.Constant.RabbitConstant;
import org.subside.Study.Mq.amqp.sender.CacheSender;
import org.subside.Study.login.mapper.LoginMapper;
import org.subside.model.admin.pojo.AdminDto;
import org.subside.model.commons.dtos.ResponseResult;
import org.subside.model.commons.enums.AppHttpCodeEnum;
import org.subside.model.commons.utils.AppJwtUtil;
import org.subside.Study.login.service.LoginService;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author : zhangbo
 * @data : 2024/3/27
 * @description :
 */
@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdminDto>implements LoginService {
    @Resource
    private CacheSender cacheSender;
    @Override
    public ResponseResult register(AdminDto dto) {
        //1.先判断用户是否注册（根据信息去匹配是否存在，并判断注册标记），未注册无法登录
        //2.用户注册后（第一次注册后登录，无需判断是否登录），将用户密码MD5加密+随机字符串
        //3.判断用户是否登录，登录后将标记写入redis，设置过期时间为一天
        Map map=new HashMap(1);
        if(dto==null||dto.getPassword()==null||dto.getUsername()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数为空!");
        }
        LambdaQueryWrapper<AdminDto> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AdminDto::getUsername,dto.getUsername()).eq(AdminDto::getPhone,dto.getPhone());
        AdminDto adminDto = getOne(wrapper);
        String register = adminDto.getIsRegister();
        if ("0".equals(register)){
            log.info("用户未注册！");
            //询问是否注册，如果是则注册，否则return拒绝登录
        }
        String jsonString = JSONObject.toJSONString(adminDto);
        List<String>list=new ArrayList<>();
        list.add(jsonString);
        cacheSender.sendMessage(list, RabbitConstant.RoutingKey.ROUTE);
        //md5 加密后存入数据库
        byte[] digest = DigestUtils.md5Digest(dto.getPassword().getBytes());
        map.put("result",adminDto==null?0:1);
        log.info("用户未注册");
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult login(AdminDto dto) {
        if(dto==null||dto.getPassword()==null||dto.getUsername()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数为空!");
        }
        //校验登录用户信息
        LambdaQueryWrapper<AdminDto> wrapper=new LambdaQueryWrapper<>();
        //根据与户名查找可能存在多个用户名相同的
        //1.根据多个条件  2.保存时校验用户名是否已经存在
        wrapper.eq(AdminDto::getUsername,dto.getUsername()).eq(AdminDto::getPhone,dto.getPhone());
        AdminDto admin = getOne(wrapper);
        //校验密码
        String pswd = dto.getPassword();
        pswd = DigestUtils.md5DigestAsHex(pswd.getBytes());
        if (!pswd.equals(admin.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //1.3 返回数据  jwt
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(admin.getId().longValue()));
        //user.setSalt("");
        admin.setPassword("");
        map.put("user", admin);
        map.put("code",200);
        admin.setLogin_time(new Date());
        admin.setUpdate_time(new Date());
        admin.setPhone(dto.getPhone());
        admin.setUpdate_person(dto.getUsername());
        updateById(admin);
        return ResponseResult.okResult(map);
    }
}
